package ls.controller;

import ls.model.Moaning;
import ls.model.Reply;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;

@Controller()
@RequestMapping("/reply")
public class ReplyController extends BaseController {
    protected static final String JSP_REPLY = "reply";

    protected static final String ATTR_REPLY = "reply";

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView getRandomMoaning(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(JSP_REPLY);
        Moaning moaning = getMoaningRepository().getRandomMoaning(); 
        request.getSession().setAttribute(ATTR_MOANING, moaning);
        putMoaning(view, moaning);
        view.addObject(ATTR_REPLY, new Reply());
        putReadOnly(view, false);
        return view;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView addReply(Reply reply, HttpServletRequest request) {
        Moaning moaning = (Moaning) request.getSession().getAttribute(ATTR_MOANING);
        getMoaningRepository().addReply(moaning.getId(), reply);
        request.getSession().removeAttribute(ATTR_MOANING);
        ModelAndView view = new ModelAndView(JSP_REPLY);
        putMoaning(view, moaning);
        view.addObject(ATTR_REPLY, reply);
        putReadOnly(view, true);
        return view;
    }
}
